<template>
  <div class="slider" ref="slider">
    <div class="slider-group" ref="sliderGroup">
    	<slot></slot>
    </div>
    <div class="dots">
    	  	<span class="dot" :class="{active: currentPageIndex === index }" v-for="(item, index) in this.dots" :key="index">
    			</span>
    </div>

  </div>
</template>

<script>
import {addClass} from 'common/js/dom'
import BScroll from 'better-scroll'
const COMPONENT_NAME = 'slide'
export default {
  name: COMPONENT_NAME,  
    data() {
      return {
        dots: [],
        currentPageIndex: 0
      }
    },
  props:{
    loop:{  // 循环轮播 自动轮播  轮播间隔
      type:Boolean,
      default:true
    },
    autoPlay:{
      type:Boolean,
      default:true
    },
    interval:{
      type:Number,
      default:4000
    },
    showDot: { // 滚动点
        type: Boolean,
        default: true
      },
      click: {
        type: Boolean,
        default: true
      },
      threshold: { //滑动的距离  阀值
        type: Number,
        default: 0.3
      },
      speed: { //滚动速度
        type: Number,
        default: 1200
      },
      pageTurn:{ //左右箭头

      }


  },
 mounted() {
      this.update()
      window.addEventListener('resize', () => {
        if (!this.slider || !this.slider.enabled) {
          return
        }
        clearTimeout(this.resizeTimer)
        this.resizeTimer = setTimeout(() => {
          if (this.slider.isInTransition) {
            this._onScrollEnd()
          } else {
            if (this.autoPlay) {
              this._play()
            }
          }
          this.refresh()
        }, 60)
      })
    },
    activated() {
      if (!this.slider) {
        return
      }
      this.slider.enable()
      let pageIndex = this.slider.getCurrentPage().pageX
      this.slider.goToPage(pageIndex, 0, 0)
      this.currentPageIndex = pageIndex
      if (this.autoPlay) {
        this._play()
      }
    },
    deactivated() { //离开页面清除timer
      this.slider.disable()
      clearTimeout(this.timer)
    },
    beforeDestroy() {
      this.slider.disable()
      clearTimeout(this.timer)
    },
  methods: {
    update() {
        if (this.slider) {
          this.slide.destroy()
        }
        this.$nextTick(() => {
          this.init()
        })
      },
      refresh() {
        this._setSliderWidth(true)
        this.slider.refresh()
      },
      prev() {
        this.slider.prev()
      },
      next() {
        this.slider.next()
      },
       init() {
        clearTimeout(this.timer)
        this.currentPageIndex = 0
        this._setSliderWidth()
        if (this.showDot) {
          this._initDots()
        }
        this._initSlider()
        if (this.autoPlay) {
          this._play()
        }
      },

    _setSliderWidth(isResize){  //给轮播图添加样式
        this.children=this.$refs.sliderGroup.children;
        console.log(this.children.length)
        let width=0;
        let sliderWidth=this.$refs.slider.clientWidth
        for (let index = 0; index < this.children.length; index++) {
             const child = this.children[index];
             addClass(child,"slider-item")
             child.style.width=sliderWidth+"px"
             width+=sliderWidth
        }
       if (this.loop && !isResize) {
          width += 2 * sliderWidth
        }
        this.$refs.sliderGroup.style.width=width+"px"
    },
    _initSlider(){ //启动better-scroll插件 https://github.com/ustbhuangyi/better-scroll/blob/master/example/components/slide/slide.vue
        this.slider=new BScroll(this.$refs.slider,{
          scrollX: true,
          scrollY: false,
          momentum: false,
          snap: {
            loop: this.loop,
            threshold: this.threshold,
            speed: this.speed,
             interval:4000
          },
          bounce: false,
          stopPropagation: true,
          click: this.click,
          pageTurn:true
        }),
        this.slider.on('scrollEnd', () => { //滚动完毕触发事件index 
          let pageIndex = this.slider.getCurrentPage().pageX
          this.currentPageIndex = pageIndex

          if (this.autoPlay) { //无线滚动
            //  clearTimeout(this.timer)
             this._play()
          }

          

        })

        this.slider.on('touchEnd', () => {
          if (this.autoPlay) {
            this._play()
          }
        })
        this.slider.on('beforeScrollStart', () => {
          if (this.autoPlay) {
            clearTimeout(this.timer)
          }
        })
    },

    // _initSlider(){ //启动better-scroll插件
    //     this.slider=new BScroll(this.$refs.slider,{
    //       scrollX:true,
    //        autoPlay:true,
    //       scrollY:false,
    //       momentum:false, //当快速在屏幕上滑动一段距离的时候，会根据滑动的距离和时间计算出动量，并生成滚动动画。设置为 true 则开启动画。
    //       // snap:true,
    //       // snapLoop:this.loop, //是否开启无缝轮播
    //       // snapThreshold:0.3, //用手指滑动时页面可切换的阀 值 大于整个阀值可以滑动到下一页
    //       // snapSpeed:400,// 轮播图切换的动画时 间
    //       click:true,
    //       snap: { //https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/options-advanced.html#snap
    //         loop: true,
    //         // auto play:
    //         threshold: 0.3,
    //         interval:4000,
    //         // autoPlay:true,
    //         // speed:400,
    //         // showDots:400,
    //         // stepX: 100,
    //         // stepY: 100,
    //         easing: {
    //           style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
    //           fn: function(t) {
    //             return t * (2 - t)
    //           }
    //         }
    //         }
    //         // bounce: { //当滚动超过边缘的时候会有一小段回弹动画。设置为 true 则开启动画。
    //         //   top: true,
    //         //   bottom: true,
    //         //   left: true,
    //         //   right: true
    //         // },
    //     })
    //     ,
    //     // this.slider.on('scrollEnd',()=>{
    //     //    let pageIndex = this.slider.getCurrentPage().pageX
    //     //   if(this.loop){
    //     //     console.log("pppp")
    //     //      pageIndex-=1;
    //     //   }
    //     //   this.currentPageIndex=parseInt;

    //     // })
    //            this.slider.on('scrollEnd', () => {
    //       let pageIndex = this.slider.getCurrentPage().pageX
    //       // if (this.loop) {
    //       //   pageIndex -= 0
    //       // }
    //       this.currentPageIndex = pageIndex

    //       // if (this.autoPlay) {
    //       //   this._play()
    //       // }
    //     })
    // },
//     _initDots(){ //轮播图下标
//       this.dots=new Array(this.children.length)
//      console.log(this.dots)
//     },
//     _play(){
//       console.log(222200000)
//        let pageIndex = this.currentPageIndex+1
//  console.log("ppppp")
//       //  pageIndex += 1
        
//         this.timer=setTimeout(()=>{
//              this.slider.goToPage(pageIndex, 0, 400)
//              console.log("ppppp")
//         },this.interval)

//         // if (this.autoPlay) {
//           //   this._play()
//           // }
//     }


      _initDots() {
        this.dots = new Array(this.children.length)
      },
      _play() {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.slider.next()
        }, this.interval)
      }


  },
    watch: {
      loop() {
        this.update()
      },
      autoPlay() {
        this.update()
      },
      speed() {
        this.update()
      },
      threshold() {
        this.update()
      }
}}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less"  scoped>
	 @import "../../common/stylus/variable.less";
	 .slider{
     min-height: 1px;
     overflow: hidden;
	 	.slider-group{
	 		position:relative;
      overflow:hidden;
      white-space: nowrap;
      .slider-item{
        float: left;
        box-sizing: border-box;
        overflow: hidden;
        text-align:center;
        a{
          display: block;
          width: 100%;
          overflow: hidden;
          text-decoration: none;
          img{
          display:block;
          width: 100%;
          height: 200px;
          overflow: hidden;
          border: 1px saddlebrown solid;
        }
        }
        
      }
     }
     .dots{
      position: absolute;
      right: 0;
      left: 0;
      bottom: 12px;
      text-align: center;
      font-size: 0;
      .dot{
        display: inline-block;
        margin: 0 4px;
        width: 8px;
        height: 8px;
        border-radius:50%;
        background: @color-text-l;
        &.active{
            width: 20px;
            border-radius:5px;
            background:@color-text-ll;
        }
      }
     }
	 }
	
	
	
	
	
	
</style>



